package com.spark.core;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

public class SparkTemplateHandler implements SparkHandler {

	private XMap screen;
	private XMap actions;
	
	private boolean haveToBreak = false;
	
	private boolean actionStarted = false;
	
	public void processDocument(XmlPullParser xpp) throws XmlPullParserException, IOException {
		int eventType = xpp.getEventType();
		do {
			if (eventType == XmlPullParser.START_TAG) {
				processStartElement(xpp);
			} else if (eventType == XmlPullParser.END_TAG) {
				processEndElement(xpp);
			} 
			eventType = xpp.next();
		} while (!haveToBreak && eventType != XmlPullParser.END_DOCUMENT);
	}
	
	private void setAttribs(XMap node, XmlPullParser xpp) {
		int count = xpp.getAttributeCount();
		for (int i = 0, l = count; i < l; i++) {
			String attrib_name = xpp.getAttributeName(i);
			node.put(attrib_name, xpp.getAttributeValue(i));
		}
	}
	public void processStartElement(XmlPullParser xpp) {
		String name = xpp.getName();
		String uri = xpp.getNamespace();
		if(SPARK_NAME_SPACE.equals(uri)){
			if(TAG_SCREEN.equals(name)) {
				screen = new XMap(SPARK_PREFIX, uri, name);
				setAttribs(screen, xpp);
			} else if(TAG_ACTIONS.equals(name)) {
				actions = new XMap(SPARK_PREFIX, uri, name);
				screen.addChild(actions);
				actionStarted = true;
			}else if (actionStarted) {
				XMap action = new XMap(SPARK_PREFIX, uri, name);
				setAttribs(action, xpp);
				actions.addChild(action);
			}
		}
	}
	
	public void processEndElement(XmlPullParser xpp) {
		String name = xpp.getName();
		String uri = xpp.getNamespace();
		if(SPARK_NAME_SPACE.equals(uri)){
			if(TAG_ACTIONS.equals(name)) {
				actionStarted = false;
				haveToBreak = true;
			}
		}
	}

	public XMap getRoot() {
		return screen;
	}
}
